package idv.loveloser.mobilemoodle;



import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ForumPostsSubjectManager extends Activity {
	private SharedPreferences sets;
	private long client;
	private String sessionKey;
	private ListView subjectListView;
	private ListView postsListView;
	private long forumId,courseId;
	private List<MdlForumDiscussions> subjects;
	private List<MdlForumPosts> posts;
	private View subjectBottomView;
	private Button addNewSubjectBtn,addNewReplyBtn;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forum_posts_manager);
    
        subjectBottomView=getLayoutInflater().inflate(R.layout.subject_bottom_view, null);
        addNewSubjectBtn =(Button) subjectBottomView.findViewById(R.id.subject_add);
        addNewSubjectBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final Dialog myDialog = new Dialog(ForumPostsSubjectManager.this);
				myDialog.setContentView(R.layout.new_subject_layout);
				final EditText newPostSubject=(EditText) myDialog.findViewById(R.id.newPostSubject);
				final EditText newPostContent = (EditText) myDialog.findViewById(R.id.newPostContent);
				final Button postItBtn=(Button) myDialog.findViewById(R.id.postItBtn);
				postItBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Util.postInFrum(client, sessionKey, courseId, forumId, 0L, newPostContent.getText().toString(), newPostSubject.getText().toString());
						myDialog.dismiss();
					}
				});
				myDialog.show();
			}
		});
        sets=getApplicationContext().getSharedPreferences("MySettings", MODE_WORLD_WRITEABLE );
        client=sets.getLong("client", -1L);
        sessionKey = sets.getString("sessionKey", "");
        courseId=getIntent().getExtras().getLong("courseId");
        forumId = getIntent().getExtras().getLong("forumId");
        subjectListView=(ListView) findViewById(R.id.subjectListView);
        subjectListView.addFooterView(subjectBottomView);
        postsListView=(ListView) findViewById(R.id.postsListView);
        String responseStr=Util.getPostsSubjectsInForum(client, sessionKey, courseId, forumId);
        Gson gson=new Gson();
        subjects=gson.fromJson(responseStr, new TypeToken<List<MdlForumDiscussions>>(){}.getType());
        ForumSubjectsAdapter subjectAdapter = new ForumSubjectsAdapter(getApplicationContext());
        subjectAdapter.setSubjects(subjects);
        subjectListView.setAdapter(subjectAdapter);
        subjectListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				MdlForumDiscussions discussion = subjects.get(position);
				String responseStr=Util.getPostsList(client, sessionKey, discussion.getId());
				Gson gson=new Gson();
				posts=gson.fromJson(responseStr, new TypeToken<List<MdlForumPosts>>(){}.getType());
				PostsAdapter postAdapter = new PostsAdapter(getApplicationContext());
				postAdapter.setClient(client);
				postAdapter.setSessionKey(sessionKey);
				postAdapter.setPosts(posts);
				postAdapter.setForumId(forumId);
				postAdapter.setCourseId(courseId);
				
				postsListView.setAdapter(postAdapter);
			}
		});
	}
	public class PostsAdapter extends BaseAdapter{
		private List<MdlForumPosts> posts;
		private Context mContext;
		private LayoutInflater mInflater;
		private long client;
		private String sessionKey;
		private long forumId=-1L;
		private long courseId=-1L;
		
		
		public PostsAdapter(Context context){
			this.mContext=context;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return posts.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int index=position;
			this.mInflater = LayoutInflater.from(mContext);
			if(posts.get(position).getParent()==0){			
				PostsHolder holder =null;
				if (convertView == null) {
					holder=new PostsHolder();
					convertView = mInflater.inflate(R.layout.posts_layout, null);
					holder.postContentTextView = (TextView) convertView.findViewById(R.id.postContent);
					holder.postCreateAtTextView = (TextView) convertView.findViewById(R.id.postCreateAt);
					holder.postUsernameTextView =(TextView) convertView.findViewById(R.id.postUsername);
					holder.actionBtn=(Button) convertView.findViewById(R.id.post_btn);
					convertView.setTag(holder); 
				}else{
					holder=(PostsHolder) convertView.getTag();
				}
				holder.postContentTextView.setText(posts.get(position).getMessage());
				Date date = new Date(posts.get(position).getCreated()*1000);
				holder.postCreateAtTextView.setText(date.toString());
				String userStr=Util.getUsernameById(client, sessionKey, posts.get(position).getUserid());
				Gson gson = new Gson();
				MdlUser user=gson.fromJson(userStr, MdlUser.class);
				String firstUsername="";
				String lastUsername="";
				try{
					firstUsername=user.getFirstname();
				}catch(NullPointerException npe){
					firstUsername="";
				}
				try{
					lastUsername=user.getLastname();
				}catch(NullPointerException npe){
					lastUsername="";
				}
				String username= firstUsername+" "+lastUsername;
				holder.postUsernameTextView.setText(username);
				
			
				holder.actionBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						final Dialog myDialog =new Dialog(ForumPostsSubjectManager.this);
						myDialog.setContentView(R.layout.new_reply_layout);
						Button postItBtn = (Button) myDialog.findViewById(R.id.replyItBtn);
						final EditText message = (EditText) myDialog.findViewById(R.id.new_reply_content);
						postItBtn.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								
								Util.postInFrum(client, sessionKey, courseId, forumId, posts.get(index).getParent(), message.getText().toString(), posts.get(index).getSubject());
								myDialog.dismiss();
							}
						});
						myDialog.show();
						
					}
				});
			}else{
				ReplyHolder holder=null;
				if (convertView == null) {
					holder=new ReplyHolder();
					convertView = mInflater.inflate(R.layout.reply_layout, null);
					holder.replyContentTextView = (TextView) convertView.findViewById(R.id.replyContent);
					holder.replyCreateAtTextView = (TextView) convertView.findViewById(R.id.replyCreateAt);
					holder.replyUsernameTextView = (TextView) convertView.findViewById(R.id.replyUsername);
					convertView.setTag(holder);
				}else{
					
					holder = (ReplyHolder) convertView.getTag();
				}
				holder.replyContentTextView.setText(posts.get(position).getMessage());
				Date date = new Date(posts.get(position).getCreated()*1000);
				holder.replyCreateAtTextView.setText(date.toString());
				String userStr=Util.getUsernameById(client, sessionKey, posts.get(position).getUserid());
				Gson gson = new Gson();
				MdlUser user=gson.fromJson(userStr, MdlUser.class);
				String firstUsername="";
				String lastUsername="";
				try{
					firstUsername=user.getFirstname();
				}catch(NullPointerException npe){
					firstUsername="";
				}
				try{
					lastUsername=user.getLastname();
				}catch(NullPointerException npe){
					lastUsername="";
				}
				String username= firstUsername+" "+lastUsername;
				holder.replyUsernameTextView.setText(username);
				
				
				holder.actionBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						final Dialog myDialog =new Dialog(ForumPostsSubjectManager.this);
						myDialog.setContentView(R.layout.new_reply_layout);
						Button postItBtn = (Button) myDialog.findViewById(R.id.replyItBtn);
						final EditText message = (EditText) myDialog.findViewById(R.id.new_reply_content);
						postItBtn.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								
								Util.postInFrum(client, sessionKey, courseId, forumId, posts.get(index).getParent(), message.getText().toString(), posts.get(index).getSubject());
								myDialog.dismiss();
							}
						});
						myDialog.show();
						
					}
				});
			}
			return convertView;
		}

		public List<MdlForumPosts> getPosts() {
			return posts;
		}

		public void setPosts(List<MdlForumPosts> posts) {
			this.posts = posts;
		}
		public long getClient() {
			return client;
		}
		public void setClient(long client) {
			this.client = client;
		}
		public String getSessionKey() {
			return sessionKey;
		}
		public void setSessionKey(String sessionKey) {
			this.sessionKey = sessionKey;
		}
		public long getForumId() {
			return forumId;
		}
		public void setForumId(long forumId) {
			this.forumId = forumId;
		}

		public long getCourseId() {
			return courseId;
		}
		public void setCourseId(long courseId) {
			this.courseId = courseId;
		}

	}
}
